<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('https://guodh.gitee.io/blog').hostname,
    root: '/blog/',
    scheme: 'Pisces',
    version: '7.7.1',
    exturl: false,
    sidebar: {"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},
    copycode: {"enable":true,"show_result":true,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    comments: {"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}
  };
</script>

  <meta name="description" content="最近公司，将线上的GC逐步配置成了G1收集器，同时Java9中G1也成为了默认的收集器。所以作为一个程序员，不得不了解下G1到底是个什么结构，凭什么他能够干掉CMS收集器。">
<meta property="og:type" content="article">
<meta property="og:title" content="CMS收集器 VS G1收集器">
<meta property="og:url" content="https://guodh.gitee.io/blog/2018/03/11/2018/CMS%E6%94%B6%E9%9B%86%E5%99%A8vsG1%E6%94%B6%E9%9B%86%E5%99%A8/index.html">
<meta property="og:site_name" content="蛋蛋的小屋">
<meta property="og:description" content="最近公司，将线上的GC逐步配置成了G1收集器，同时Java9中G1也成为了默认的收集器。所以作为一个程序员，不得不了解下G1到底是个什么结构，凭什么他能够干掉CMS收集器。">
<meta property="og:locale">
<meta property="og:image" content="https://olwr1lamu.qnssl.com/Animation_of_the_Naive_Mark_and_Sweep_Garbage_Collector_Algorithm.gif">
<meta property="og:image" content="https://olwr1lamu.qnssl.com/Animation_of_tri-color_garbage_collection.gif">
<meta property="og:image" content="https://olwr1lamu.qnssl.com/g1heap.png">
<meta property="og:image" content="https://olwr1lamu.qnssl.com/after.jpg">
<meta property="og:image" content="https://olwr1lamu.qnssl.com/G1%E6%B8%85%E7%90%86%E8%BF%87%E7%A8%8B.png">
<meta property="article:published_time" content="2018-03-11T11:40:41.000Z">
<meta property="article:modified_time" content="2018-03-11T14:26:50.000Z">
<meta property="article:author" content="RunningEgg">
<meta property="article:tag" content="JVM">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://olwr1lamu.qnssl.com/Animation_of_the_Naive_Mark_and_Sweep_Garbage_Collector_Algorithm.gif">

<link rel="canonical" href="https://guodh.gitee.io/blog/2018/03/11/2018/CMS%E6%94%B6%E9%9B%86%E5%99%A8vsG1%E6%94%B6%E9%9B%86%E5%99%A8/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>CMS收集器 VS G1收集器 | 蛋蛋的小屋</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">蛋蛋的小屋</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">来了就看看吧，没有刀剑只有故事</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-fw fa-home"></i>Home</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-fw fa-user"></i>About</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>Archives</a>

  </li>
        <li class="menu-item menu-item-book">

    <a href="/blog/book/" rel="section"><i class="fa fa-fw fa-archive"></i>book</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://guodh.gitee.io/blog/2018/03/11/2018/CMS%E6%94%B6%E9%9B%86%E5%99%A8vsG1%E6%94%B6%E9%9B%86%E5%99%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.gif">
      <meta itemprop="name" content="RunningEgg">
      <meta itemprop="description" content="写下我的点点滴滴，写下我对这个世界的看法，还有我内心锁崇拜的技术">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="蛋蛋的小屋">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          CMS收集器 VS G1收集器
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>
              

              <time title="Created: 2018-03-11 19:40:41 / Modified: 22:26:50" itemprop="dateCreated datePublished" datetime="2018-03-11T19:40:41+08:00">2018-03-11</time>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>最近公司，将线上的GC逐步配置成了G1收集器，同时Java9中G1也成为了默认的收集器。所以作为一个程序员，不得不了解下G1到底是个什么结构，凭什么他能够干掉CMS收集器。</p>
<a id="more"></a>

<h2 id="CMS收集器"><a href="#CMS收集器" class="headerlink" title="CMS收集器"></a>CMS收集器</h2><p>既然是CMS收集器和G1收集器的比较，那么的先来讲清楚CMS收集器是个什么东西。CMS收集器，英文名是Concurrent Mark Sweep Garbage Collection（并发标记垃圾清扫收集器），其实你看英语名就知道CMS到底在哪里有了巨大的提升。</p>
<h3 id="CMS收集器出现前的时代"><a href="#CMS收集器出现前的时代" class="headerlink" title="CMS收集器出现前的时代"></a>CMS收集器出现前的时代</h3><p>继续举那个例子，小明在卧室吃东西丢垃圾，然而小明的妈妈要定时来打扫垃圾，如果边打扫小明还继续丢垃圾，势必卧室就还是脏的，解决办法就只能是小明停止吃东西，妈妈先打扫。OK，这就是比较典型的serial收集器，parallel收集器……</p>
<p>这种情况下，无论是单线程还是多线程，他们都需要小明（或者说是jvm）停止生产垃圾，也就是STOP THE WORLD。</p>
<p>在更规范一点的讲，因为serial收集器，parallel收集器都是靠着可达性分析来判断，是否将这个对象标记为可回收的对象。看下面一张图：</p>
<img src="https://olwr1lamu.qnssl.com/Animation_of_the_Naive_Mark_and_Sweep_Garbage_Collector_Algorithm.gif"  alt="Animation_of_the_Naive_Mark_and_Sweep_Garbage_Collector_Algorithm"/>


<p>里面存在一个最大的问题，遍历和标记是在一起的。也就是说，它遍历所有的节点，同时边遍历边标记。那么导致jvm需要停止很长的时间。所以解决方案就是能否将标记和遍历分离，减少STW的时间。OK，这就是Concurrent Mark Sweep Garbage。 </p>
<h2 id="CMS的原理"><a href="#CMS的原理" class="headerlink" title="CMS的原理"></a>CMS的原理</h2><p>CMS的原理就是传说中的三色标记算法。（其实很简单的，慢慢来看）</p>
<img src="https://olwr1lamu.qnssl.com/Animation_of_tri-color_garbage_collection.gif"  alt="Animation_of_tri-color_garbage_collection"/>


<blockquote>
<p>三色标记算法是对标记阶段的改进，原理如下：</p>
</blockquote>
<ol>
<li>首先创建三个集合：白、灰、黑。</li>
<li>将所有对象放入白色集合中。</li>
<li>然后从根节点开始遍历所有对象（注意这里并不递归遍历），把遍历到的对象从白色集合放入灰色集合。</li>
<li>之后遍历灰色集合，将灰色对象引用的对象从白色集合放入灰色集合，之后将此灰色对象放入黑色集合</li>
<li>重复 4 直到灰色中无任何对象</li>
<li>重新标记步骤4，5期间产生的对象（go 中使用）</li>
<li>收集所有白色对象（垃圾）</li>
</ol>
<p>来看下CMS(Concurrent Mark Sweep) 收集器具体的实现：</p>
<ol>
<li>initial mark -&gt; stop the world</li>
<li>concurrent mark -&gt; GC Root Tracing</li>
<li>remark -&gt; stop world</li>
<li>concurrent sweep</li>
</ol>
<p><strong>步骤1</strong>表示遍历Root set，将对象放入灰色区域，对应三色标记的3<br><strong>步骤2</strong>表示遍历灰色区域的对象，但这时是并发进行的，是不会造成STOP THE WORLD，对应的是三色标记4，5<br><strong>步骤3</strong>是重新标记在步骤2中，同步进行所遗漏的对象<br><strong>步骤4</strong>将没有标记的对象，全部清除</p>
<h2 id="G1收集器"><a href="#G1收集器" class="headerlink" title="G1收集器"></a>G1收集器</h2><h3 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h3><p>先来看下G1官网对G1的介绍</p>
<blockquote>
<p>The Garbage-First (G1) collector is a server-style garbage collector, targeted for multi-processor machines with large memories. It meets garbage collection (GC) pause time goals with a high probability, while achieving high throughput. The G1 garbage collector is fully supported in Oracle JDK 7 update 4 and later releases. The G1 collector is designed for applications that:</p>
</blockquote>
<blockquote>
<ol>
<li>Can operate concurrently with applications threads like the CMS collector.</li>
<li>Compact free space without lengthy GC induced pause times.</li>
<li>Need more predictable GC pause durations.</li>
<li>Do not want to sacrifice a lot of throughput performance.</li>
<li>Do not require a much larger Java heap.</li>
</ol>
</blockquote>
<p>G1是一个为了大内存设计的多线程处理的垃圾回收器。它能满足大吞吐量的时候，GC停止时间的要求。C1完全支持JDK 7 update 4 及以后的 JDK版本。G1是为以下几种需求设计：</p>
<ol>
<li>能够和应用线程一起运行</li>
<li>为了减少暂停时间，能够进行空间合并，而且不需要长时间的GC</li>
<li>能够预测GC时间</li>
<li>不影响吞吐性能</li>
<li>不要求更大的java堆</li>
</ol>
<h3 id="与CMS收集器区别"><a href="#与CMS收集器区别" class="headerlink" title="与CMS收集器区别"></a>与CMS收集器区别</h3><p>相比于CMS是不是更符合现在这个互联网时代，动辄16G，32G内存的服务器。so，一起来看下区别：</p>
<img src="https://olwr1lamu.qnssl.com/g1heap.png"  alt="G1heap"/>
可以看到，和CMS收集器完全不同，G1中没有固定的年轻代，老年代的区别，G1将heap直接分为了一个个小的region。这样就可以用更小的颗粒度来控制heap，同时能够使用更好的压缩使用空间。

<h3 id="Young-GC"><a href="#Young-GC" class="headerlink" title="Young GC"></a>Young GC</h3><img src="https://olwr1lamu.qnssl.com/after.jpg"  alt="Young GC"/>
可以看到，相比于CMS收集器，G1收集器多了一步压缩。能够将一些没清理的对象，统一放到一个region中，这样减少了下一次GC的成本。

<p><strong>需要注意的是：无论什么收集器的Young GC 都会SOTP THE WORLD，包括CMS和G1的。</strong></p>
<h3 id="Old-Generation-Collection-with-G1"><a href="#Old-Generation-Collection-with-G1" class="headerlink" title="Old Generation Collection with G1"></a>Old Generation Collection with G1</h3><p>发现网上的资料比较少，而且还缺少比较统一的说法，为了不误导大家，把官网的介绍给搬了过来。<br><img src="https://olwr1lamu.qnssl.com/G1%E6%B8%85%E7%90%86%E8%BF%87%E7%A8%8B.png"  alt="G1清理过程"/></p>
<p>可以看到G1也是和CMS一样使用了三色标记算法，然而不同的是G1使用了SATB，以及RSET等辅助工具来帮助进行GC。同时还增加了重置region的步骤。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><ol>
<li>G1用更小的颗粒度来控制heap，同时能够通过移动region来压缩heap</li>
<li>老年代的GC本质上都是三色标记算法，通过分离标记和遍历，来达到多线程并行的效果</li>
<li>G1还有更多的细节需要理解，包括如何控制GC时间，如何优化三色标记算法。利用空余时间继续研究jvm~</li>
</ol>
<h2 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h2><ol>
<li>一张图了解三色标记法 <a href="http://idiotsky.me/2017/08/16/gc-three-color/">http://idiotsky.me/2017/08/16/gc-three-color/</a></li>
<li>Golang 垃圾回收剖析 <a href="http://legendtkl.com/2017/04/28/golang-gc/">http://legendtkl.com/2017/04/28/golang-gc/</a></li>
<li>官方介绍 <a href="http://www.oracle.com/technetwork/tutorials/tutorials-1876574.html">http://www.oracle.com/technetwork/tutorials/tutorials-1876574.html</a></li>
</ol>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/JVM/" rel="tag"># JVM</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2018/03/03/2018/JVM%E7%BA%BF%E4%B8%8A%E9%97%AE%E9%A2%98%E6%8E%92%E6%9F%A5%E5%B7%A5%E5%85%B7/" rel="prev" title="JVM线上问题排查工具">
      <i class="fa fa-chevron-left"></i> JVM线上问题排查工具
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2018/04/21/2018/2018-04-19/" rel="next" title="数据库MVCC、事务回滚">
      数据库MVCC、事务回滚 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#CMS%E6%94%B6%E9%9B%86%E5%99%A8"><span class="nav-number">1.</span> <span class="nav-text">CMS收集器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#CMS%E6%94%B6%E9%9B%86%E5%99%A8%E5%87%BA%E7%8E%B0%E5%89%8D%E7%9A%84%E6%97%B6%E4%BB%A3"><span class="nav-number">1.1.</span> <span class="nav-text">CMS收集器出现前的时代</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#CMS%E7%9A%84%E5%8E%9F%E7%90%86"><span class="nav-number">2.</span> <span class="nav-text">CMS的原理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#G1%E6%94%B6%E9%9B%86%E5%99%A8"><span class="nav-number">3.</span> <span class="nav-text">G1收集器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BB%8B%E7%BB%8D"><span class="nav-number">3.1.</span> <span class="nav-text">介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%8ECMS%E6%94%B6%E9%9B%86%E5%99%A8%E5%8C%BA%E5%88%AB"><span class="nav-number">3.2.</span> <span class="nav-text">与CMS收集器区别</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Young-GC"><span class="nav-number">3.3.</span> <span class="nav-text">Young GC</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Old-Generation-Collection-with-G1"><span class="nav-number">3.4.</span> <span class="nav-text">Old Generation Collection with G1</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99"><span class="nav-number">5.</span> <span class="nav-text">参考资料</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">RunningEgg</p>
  <div class="site-description" itemprop="description">写下我的点点滴滴，写下我对这个世界的看法，还有我内心锁崇拜的技术</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">89</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">24</span>
        <span class="site-state-item-name">tags</span>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="mailto:guodh_1@163.com" title="E-Mail → mailto:guodh_1@163.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">RunningEgg</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> v5.3.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">Theme – <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.7.1
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  















  

  

</body>
</html>
